package com.sky.service.impl;


import com.sky.dto.AmountAndOrderTImeDTo;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnOverStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        //生成横坐标时间参数
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);
        //生成纵坐标金钱总额

        //得到满足交易时间在begin到end之间且订单状态为已完成的所有订单数据的钱和下单时间
        List<AmountAndOrderTImeDTo> list = orderMapper.amountAndOrderTime(beginTime,endTime, Orders.COMPLETED);

        List<BigDecimal> allAmountList = new ArrayList<>();
        //循环时间集合，将满足该时间段的所有数据加起来
        for (LocalDate localDate : dateList) {
            beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            BigDecimal allAmount = new BigDecimal(0);
            for (AmountAndOrderTImeDTo DB : list) {
                if(beginTime.isBefore(DB.getOrderTime()) && DB.getOrderTime().isBefore(endTime)){
                    allAmount = allAmount.add(DB.getAmount());
                }
                //由于是有序的集合，所以超出这个时间就可以进行下一天的金额总和
                if(endTime.isBefore(DB.getOrderTime())){
                    break;
                }
            }
            allAmountList.add(allAmount);
        }

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(allAmountList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserOverStatistics(LocalDate begin, LocalDate end) {
        //得到总的时间段的一个开始时间和结束时间
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        //生成横坐标时间参数
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        List<User> userList = userMapper.getByCreateTime(beginTime,endTime);
        //存放每天新增用户数量
        List<Integer> newUserList = new ArrayList<>();
        //存放每天总的用户数量
        List<Integer> totalUserList = new ArrayList<>();
        //循环时间集合，将满足该时间段的所有数据加起来
        for (LocalDate localDate : dateList) {
            //得到每一天的开始时间和结束时间
            beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            endTime = LocalDateTime.of(localDate,LocalTime.MAX);

            Integer num = 0;
            for (User user : userList) {
                //确定每天新增的用户数量
                if(beginTime.isBefore(user.getCreateTime()) && user.getCreateTime().isBefore(endTime)){
                    num += 1;
                }
                //由于是有序的集合，所以超出这个时间就可以进行下一天的人数总和
                if(endTime.isBefore(user.getCreateTime())){
                    break;
                }
            }
            newUserList.add(num);
            if(totalUserList.isEmpty()){
                totalUserList.add(num);
            }else{
                totalUserList.add(num+ totalUserList.get(totalUserList.size()-1));
            }
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersOverStatistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        //生成横坐标时间参数
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        dateList.add(end);

        //每日订单数，以逗号分隔，例如：260,210,215
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数，以逗号分隔，例如：20,21,10
        List<Integer> validOrderCountList = new ArrayList<>();

        List<Orders> list = orderMapper.getByCreateTime(beginTime,endTime);

        for (LocalDate localDate : dateList) {
            beginTime = LocalDateTime.of(localDate,LocalTime.MIN);
            endTime = LocalDateTime.of(localDate,LocalTime.MAX);
            Integer orderCount = 0;
            Integer validOrderCount1 = 0;
            for (Orders orders : list) {
                if(beginTime.isBefore(orders.getOrderTime()) && orders.getOrderTime().isBefore(endTime)){
                    if(Orders.COMPLETED.equals(orders.getStatus())){
                        validOrderCount1 ++;
                    }
                    orderCount++;
                }
                //由于是有序的集合，所以超出这个时间就可以进行下一天的人数总和
                if(endTime.isBefore(orders.getOrderTime())){
                    break;
                }
            }
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount1);
        }
        //订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率

        Double orderCompletionRate = 0.0;

        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .build();
    }

    /**
     * 查询统计销量前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.getSalesTop(beginTime,endTime);

        List<String> name = goodsSalesDTO.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> number = goodsSalesDTO.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(name,","))
                .numberList(StringUtils.join(number,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于模板文件创建一个新的 excel文件
        try {
            XSSFWorkbook excecl = new XSSFWorkbook(in);

            //获取表格文件的sheet页
            XSSFSheet sheet = excecl.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+dateBegin+"至"+dateEnd);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第五行
            row = sheet.getRow(5);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //某一天的营业额数据
                BusinessDataVO businessDatavo = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDatavo.getTurnover());
                row.getCell(3).setCellValue(businessDatavo.getValidOrderCount());
                row.getCell(4).setCellValue(businessDatavo.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDatavo.getUnitPrice());
                row.getCell(6).setCellValue(businessDatavo.getNewUsers());
            }


            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excecl.write(out);

            //关闭资源
            out.close();
            excecl.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



    }
}
